document.addEventListener('DOMContentLoaded', function() {
    // 在i18n初始化完成后，确保页面文本已翻译
    if (window.i18n) {
        i18n.translatePage();
    }
    
    // 获取DOM元素
    const backButton = document.querySelector('.back-button');
    const registerForm = document.getElementById('register-form');
    const nameInput = document.getElementById('name');
    const emailInput = document.getElementById('email');
    const passwordInput = document.getElementById('password');
    const confirmPasswordInput = document.getElementById('confirm-password');
    const agreeTermsCheckbox = document.getElementById('agree-terms');
    const registerButton = document.getElementById('register-button');
    const errorMessage = document.getElementById('error-message');
    const loadingOverlay = document.getElementById('loading-overlay');
    const togglePasswordButtons = document.querySelectorAll('.toggle-password');
    const strengthLevel = document.getElementById('strength-level');
    const strengthText = document.getElementById('strength-text');
    const strengthValue = document.getElementById('strength-value');
    
    // 检查是否有重定向URL
    const params = new URLSearchParams(window.location.search);
    const redirectUrl = params.get('redirect') || '../index.html';
    
    // 如果用户已登录，直接重定向
    if (apiService.isLoggedIn()) {
        window.location.href = redirectUrl;
        return;
    }
    
    // 返回按钮事件
    backButton.addEventListener('click', function() {
        window.history.back();
    });
    
    // 切换密码可见性
    togglePasswordButtons.forEach(button => {
        button.addEventListener('click', function() {
            const input = this.parentElement.querySelector('input');
            const type = input.getAttribute('type') === 'password' ? 'text' : 'password';
            input.setAttribute('type', type);
            
            // 切换眼睛图标
            const eyeIcon = this.querySelector('.eye-icon');
            eyeIcon.src = type === 'password' ? '../images/eye.svg' : '../images/eye-off.svg';
        });
    });
    
    // 监控密码强度
    passwordInput.addEventListener('input', function() {
        const password = this.value;
        const strength = checkPasswordStrength(password);
        
        // 更新强度指示器
        strengthLevel.style.width = `${strength.percent}%`;
        strengthLevel.className = 'strength-level';
        strengthLevel.classList.add(strength.level);
        
        // 更新强度文本
        let strengthTextKey = 'password_weak';
        if (strength.level === 'medium') {
            strengthTextKey = 'password_medium';
        } else if (strength.level === 'strong') {
            strengthTextKey = 'password_strong';
        }
        
        if (window.i18n) {
            strengthValue.textContent = i18n.t(strengthTextKey);
            strengthValue.setAttribute('data-i18n', strengthTextKey);
        } else {
            // 回退到默认文本
            const strengthTexts = {
                'weak': '弱',
                'medium': '中',
                'strong': '强'
            };
            strengthValue.textContent = strengthTexts[strength.level];
        }
    });
    
    // 表单提交
    registerForm.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        // 获取表单数据
        const name = nameInput.value.trim();
        const email = emailInput.value.trim();
        const password = passwordInput.value;
        const confirmPassword = confirmPasswordInput.value;
        const agreeTerms = agreeTermsCheckbox.checked;
        
        // 表单验证
        if (!name) {
            showError(i18n ? i18n.t('error_register') : '注册失败，请稍后再试');
            nameInput.focus();
            return;
        }
        
        if (!email || !validateEmail(email)) {
            showError(i18n ? i18n.t('error_register') : '注册失败，请稍后再试');
            emailInput.focus();
            return;
        }
        
        if (!password || password.length < 6) {
            showError(i18n ? i18n.t('error_register') : '注册失败，请稍后再试');
            passwordInput.focus();
            return;
        }
        
        if (password !== confirmPassword) {
            showError(i18n ? i18n.t('error_register') : '注册失败，请稍后再试');
            confirmPasswordInput.focus();
            return;
        }
        
        if (!agreeTerms) {
            showError(i18n ? i18n.t('error_register') : '注册失败，请稍后再试');
            return;
        }
        
        // 显示加载状态
        showLoading(true);
        
        try {
            // 调用注册API
            const result = await apiService.register(name, email, password);
            
            // 注册成功，重定向到登录页或指定的页面
            window.location.href = redirectUrl;
        } catch (error) {
            console.error('注册失败:', error);
            showError(i18n ? i18n.t('error_register') : '注册失败，请稍后再试');
            showLoading(false);
        }
    });
    
    // 显示错误消息
    function showError(message) {
        errorMessage.textContent = message;
        errorMessage.style.display = 'block';
        
        // 3秒后自动隐藏
        setTimeout(() => {
            errorMessage.style.display = 'none';
        }, 3000);
    }
    
    // 控制加载状态
    function showLoading(show) {
        if (show) {
            loadingOverlay.classList.add('show');
            registerButton.disabled = true;
        } else {
            loadingOverlay.classList.remove('show');
            registerButton.disabled = false;
        }
    }
    
    // 验证邮箱格式
    function validateEmail(email) {
        const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(email.toLowerCase());
    }
    
    // 检查密码强度
    function checkPasswordStrength(password) {
        // 长度评分
        const lengthScore = Math.min(password.length / 10, 1);
        
        // 复杂性评分
        let complexityScore = 0;
        if (/[a-z]/.test(password)) complexityScore += 0.25;
        if (/[A-Z]/.test(password)) complexityScore += 0.25;
        if (/[0-9]/.test(password)) complexityScore += 0.25;
        if (/[^a-zA-Z0-9]/.test(password)) complexityScore += 0.25;
        
        // 总评分（0-1之间）
        const totalScore = (lengthScore + complexityScore) / 2;
        
        // 确定强度级别
        let level = 'weak';
        let percent = totalScore * 100;
        
        if (totalScore >= 0.7) {
            level = 'strong';
        } else if (totalScore >= 0.4) {
            level = 'medium';
        }
        
        return {
            level,
            percent
        };
    }
    
    // 监听语言变更事件
    window.addEventListener('message', function(event) {
        // 确保消息来源可信
        if (event.origin !== window.location.origin) return;
        
        // 处理语言变更消息
        if (event.data && event.data.type === 'language-change') {
            const language = event.data.language;
            
            // 如果页面有i18n对象，应用语言变更
            if (window.i18n) {
                window.i18n.changeLanguage(language);
                
                // 更新密码强度显示
                const strength = checkPasswordStrength(passwordInput.value);
                let strengthTextKey = 'password_weak';
                if (strength.level === 'medium') {
                    strengthTextKey = 'password_medium';
                } else if (strength.level === 'strong') {
                    strengthTextKey = 'password_strong';
                }
                
                strengthValue.textContent = i18n.t(strengthTextKey);
                strengthValue.setAttribute('data-i18n', strengthTextKey);
            }
        }
    });
}); 